package itsm.isperp.framework.exception;

import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 异常传递器
 * 
 * @author lizx
 * @date 2013-3-3
 * @version V1.0
 * 
 */
@Aspect
@Service
public class ExceptionTransfer {

	public static final Logger logger = LoggerFactory
			.getLogger(ExceptionTransfer.class);

	@Pointcut("execution(* itsm.isperp.*.*Service.*(..)) || execution(* itsm.isperp..*Service.*(..)) || execution(* itsm.isperp.*.*Controller.*(..)) || execution(* itsm.isperp..*Controller.*(..))")
	public void serviceMethod() {
	}

	@AfterThrowing(pointcut = "serviceMethod()", throwing = "exception")
	public void transfer(JoinPoint thisJoinPoint, Exception exception)
			throws Exception {
		// Object target = thisJoinPoint.getTarget();
		Object[] arguments = thisJoinPoint.getArgs();
		for (Object arg : arguments) {
			if (arg instanceof HttpServletResponse) {
				StringBuilder messageBuilder = new StringBuilder(
						exception.toString() + "\r\n");
				StackTraceElement[] trace = exception.getStackTrace();
				for (int i = 0; i < trace.length; i++) {
					messageBuilder.append("\tat " + trace[i] + "\r\n");
				}

				HttpServletResponse response = (HttpServletResponse) arg;
				ObjectMapper objectMapper = new ObjectMapper();

				objectMapper.writeValue(response.getOutputStream(),
						exception.toString());
				return;
			}
		}

	}
}
